from typing import List, Dict, Optional
from app.config.config import settings
from app.tools.redis_client import redis_client
from app.schemas.assets_schema import TextRule
from app.schemas.facenet_base_schema import AlgorithmResponse, OutputParams, TaskStatus, AlgorithmMiddleResponse
from app.utils.logger import logger
import traceback
from app.utils.llm_client import LLMClient

class AlgoCodeService:
    def __init__(self):
        # add your code
        pass

    async def update_task_status(self, task_id: str, task_data: dict, progress: int, logs: str):
        """更新任务状态"""
        try:
            response = AlgorithmMiddleResponse(
                task_id=task_id,
                task_callback_url=task_data.get("task_callback_url"),
                task_status=TaskStatus.RUNNING,
                task_progress=progress,
                task_logs=logs,
                input_params=task_data.get("input_params"),
                metrics=[]
            )
            # 使用 model_dump() 确保数据可序列化
            await redis_client.update_data(f'{task_id}_result', response.model_dump())
            logger.info(f"任务状态更新成功: {task_id}, 进度: {progress}%, 日志: {logs}")
        except Exception as e:
            logger.error(f"任务状态更新失败: {task_id}, 错误: {str(e)}")
            raise
 
    async def extract_yours_service(self, input_params : dict, task_id: str) -> AlgorithmResponse:
        """主要的函数"""
        task_data = await redis_client.get_data(task_id)
        input_params = task_data.get("input_params")
        try:   
            # 你的代码逻辑 TODO
            pass
            #存储中间状态
            await self.update_task_status(task_id, task_data, 10, "记录重要的日志 比如结果 状态等")
            # 返回最终结果
            return AlgorithmResponse(
                task_id=task_id,
                task_callback_url=task_data.get("task_callback_url"),
                task_status=TaskStatus.COMPLETED,
                task_progress=100,
                output_params={
                    "输出结果": "输出的本体类型"# TODO
                },
                metrics=[]
            )
        except Exception as e:
            error_msg = f"错误: {str(e)}\n{traceback.format_exc()}"
            # 更新任务状态为失败
            error_response = AlgorithmMiddleResponse(
                task_id=task_id,
                task_callback_url=task_data.get("task_callback_url"),
                task_status=TaskStatus.FAILED,
                task_progress=0,
                task_logs=error_msg,
                input_params=task_data.get("input_params"),
                metrics=[]
            )
            await redis_client.update_data(f'{task_id}_result', error_response.model_dump())
            raise 

